package com.example.dell.avtivity;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import Adapter.SearchrecycleViewAdapter;
import Animator.TextView_error;
import MyInterface.RecycleItemListener;
import MyListener.RecycleListener;
import MyView.MyDecoration;
import MyView.SearchLayout;
import MyView.myLinearlayout;
import MyView.mySwipeLayout;
import NetRequest.SendRuest;
import bean.HotSearch;
import bean.Searched;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * Created by dell on 2017/3/18.
 */

public class Search extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "TAG";

    private int maxRuest;
    public String status;
    private int footer_status;
    String searchthing;
    //UI
    MyView.mySwipeLayout refreshLayout;
    ProgressBar progressBar;
    ImageView back, cancel, refresh;
    TextView change_tx;
    EditText editText;
    SearchLayout searchLayout;
    LinearLayout lin;
    GradientDrawable drawable = null;
    ViewGroup.MarginLayoutParams lp;
    //    SwipeRefreshLayout refreshLayout;
    RecyclerView recyclerView = null;
    HotSearch hotSearch;
    Searched searched;
    SearchrecycleViewAdapter adapter;
    List<String> data_num = new ArrayList();
    List<String> texts = new ArrayList<>();
    List<bean.Searched.DataBean> list = new ArrayList<>();
    int width = ViewGroup.MarginLayoutParams.WRAP_CONTENT;
    int height = ViewGroup.MarginLayoutParams.WRAP_CONTENT;


    private SendRuest sr = new SendRuest();
    private int GO = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case INIHOTVIEWFAIL:
                    GO = 1;
                    Toast.makeText(Search.this, "连接超时", Toast.LENGTH_SHORT).show();
                    break;
                case INIHOTVIEWSUCCESS:
                    texts.clear();
                    texts = hotSearch.getData();
                    ramdomnum(texts);
                    showTextView();
                    GO = 1;
                    break;
                case GOTOSEARCH:
                    try {
                        refreshLayout.setVisibility(View.VISIBLE);
                        list = searched.getData();
                        if (list.size() >= 1) {
                            page++;
                        }else {
                            Toast.makeText(Search.this, "没有你要的零食哦", Toast.LENGTH_SHORT).show();
                        }
                        adapter = new SearchrecycleViewAdapter(Search.this, list);
                        if (recycleItemListener==null){
                            adapter.setOnItemClickListener(new RecycleItemListener() {
                                @Override
                                public void onclick(View view, int id) {
                                    Log.d(TAG, "onclick: "+id);
                                }
                            });
                        }
                        recyclerView.setLayoutManager(new myLinearlayout(Search.this, LinearLayoutManager.VERTICAL, false));
                        recyclerView.setAdapter(adapter);
                        refreshLayout.setRefreshing(false);
                        progressBar.setVisibility(View.GONE);
                        refreshLayout.setRefreshing(false);
                    } catch (NullPointerException e) {
                        Toast.makeText(Search.this, "请勿多次刷新", Toast.LENGTH_SHORT).show();
                        refreshLayout.setRefreshing(false);
                    } catch (IndexOutOfBoundsException e) {
                        Log.d(TAG, "handleMessage: ");
                        Toast.makeText(Search.this, "请勿多次刷新", Toast.LENGTH_SHORT).show();
                        refreshLayout.setRefreshing(false);
                    }
                    break;
                case LOGINMOREDATA:
                    try {
                        Log.d("TAG", "size" + searched.getData().size() + "..." + page);
                        List listnew = new ArrayList();
                        listnew = searched.getData();
                        if (listnew.size() > 1) {
                            page += 1;
                            maxRuest++;
                            adapter.addall(list, listnew);
                            showFooter(NORMAL);
                        } else {
                            footer_status = END;
                            showFooter(footer_status);
                        }
                    } catch (NullPointerException e) {
                        Toast.makeText(Search.this, "刷新太快啦", Toast.LENGTH_SHORT).show();
                        refreshLayout.setRefreshing(false);
                        showFooter(NORMAL);
                    }
                    break;
                case ERRORDATA:
                    footer_status = ERROR;
                    showFooter(footer_status);
                    refreshLayout.setRefreshing(false);
                    break;
                case GOTOSEARCH_FAIL:
                    refreshLayout.setRefreshing(false);
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(Search.this, "服务器出问题啦,请稍后重试", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private final int INIHOTVIEWSUCCESS = 1;
    private final int INIHOTVIEWFAIL = 2;
    private final int GOTOSEARCH = 3;
    private final int LOGINMOREDATA = 4;
    private final int ERRORDATA = 5;
    private final int GOTOSEARCH_FAIL = 6;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ActionBar actionbar = getSupportActionBar();
        if (actionbar != null) {
            actionbar.hide();
        }
        try {
            searchLayout = (SearchLayout) findViewById(R.id.searchview);
            lin = (LinearLayout) findViewById(R.id.lin);
            initHotView();

            progressBar = (ProgressBar) findViewById(R.id.search_progress);
            recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
            recyclerView.addOnScrollListener(mylistener);
            recyclerView.setOnTouchListener(onTouchListener);
            recyclerView.addItemDecoration(new MyDecoration(40,10));
            adapter = new SearchrecycleViewAdapter(Search.this, list);
            back = (ImageView) findViewById(R.id.back_search);
            cancel = (ImageView) findViewById(R.id.cancal_search);
            refresh = (ImageView) findViewById(R.id.refresh_search);
            change_tx = (TextView) findViewById(R.id.change_tx);
            change_tx.setOnClickListener(this);
            back.setOnClickListener(this);
            cancel.setOnClickListener(this);
            refresh.setOnClickListener(this);

            //搜索按钮
            editText = (EditText) findViewById(R.id.edittext_search);
            editText.setOnClickListener(this);
            editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        searchthing = editText.getText().toString();
                        if (!searchthing.isEmpty()) {
                            page = 1;
                            maxRuest = 0;
                            list.clear();
                            searched = null;
                            SearchProduct(searchthing, page);
                            progressBar.setVisibility(View.VISIBLE);
                            lin.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                        } else {
                            TextView_error.tada(editText, (float) 0.9).start();
//                            TextView_error.nope(back).start();
                            TextView_error.SetAnimator(cancel);
                            Toast.makeText(Search.this, "请输入你要查找的零食", Toast.LENGTH_SHORT).show();
                        }
                    }
                    return false;
                }
            });
            //下拉刷新
            refreshLayout = (mySwipeLayout) findViewById(R.id.refreshlayout);
            refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    try {
                        refreshLayout.setRefreshing(true);
                        progressBar.setVisibility(View.GONE);
                        page = 1;
                        maxRuest = 0;
                        list.clear();
                        if (searched.getData() != null) {
                            searched.getData().clear();
                            searched = null;
                            Log.d(TAG, "onRefresh: ");
                        }
                        SearchProduct(searchthing, page);
                        recyclerView.setVisibility(View.VISIBLE);
                    } catch (NullPointerException E) {
                        E.printStackTrace();
                        refreshLayout.setRefreshing(false);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            refreshLayout.setRefreshing(false);
        }

    }

    /*
    Searchlayout中加入data_num中的textview
     */
    private void showTextView() {
        for (int i = 0; i < data_num.size(); i++) {
            final TextView textView = new TextView(Search.this);
            textView.setTag(i);
            textView.setTextSize(15);
            textView.setText(data_num.get(i).toString());
            textView.setPadding(24, 11, 24, 11);
            textView.setTextColor(Color.BLACK);
            textView.setBackgroundResource(R.drawable.searchitem);
            drawable = (GradientDrawable) textView.getBackground();
            drawable.setColor(randomcolor());
            textView.getBackground().setAlpha(25);
            lp = new ViewGroup.MarginLayoutParams(width, height);
            lp.setMargins(30, 30, 30, 30);
            searchLayout.addView(textView, lp);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(Search.this, data_num.get((Integer) textView.getTag()), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /*
    产生随机颜色
     */
    private int randomcolor() {
        Random rnd = new Random();
        int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
                rnd.nextInt(256));
        return color;
    }

    /*
    从texts表随机生成九个，放入datanum表
     */
    private void ramdomnum(List<String> list) {
        if (list.size() == 0) {
            list.clear();
            list.add("服务器爆炸了，等会再刷");
        }
//        searchLayout.removeAllViews();
        data_num.clear();
        List<Integer> list_cache = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            Random random = new Random();
            int num = random.nextInt(list.size());
            if (!list_cache.contains(num)) {
                list_cache.add(num);
                data_num.add(list.get(num));
            }
            if (data_num.size() == 9) {
                break;
            }
        }
        list_cache.clear();
    }


    /*
    发送请求，得到热门搜索的list
     */
    private void initHotView() {
        sr.ShowHot(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("TAG", "initHotView respponseFail");
                Message message = new Message();
                message.what = INIHOTVIEWFAIL;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("TAG", "initHotView respponseSuccess");
                String responsedata = response.body().string();
                Gson gson = new Gson();
                try {
                    hotSearch = gson.fromJson(responsedata, HotSearch.class);
                    Message message = new Message();
                    message.what = INIHOTVIEWSUCCESS;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = INIHOTVIEWFAIL;
                    handler.sendMessage(message);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_search:
                break;
            case R.id.cancal_search:
                editText.setText("");
                break;
            case R.id.change_tx:
                try {
                    if (texts.size() < 2) {
                        if (searchLayout.getChildCount() != 0) {
                            searchLayout.removeAllViews();
                        }
                        if (GO == 1) {
                            initHotView();
                            GO = 0;
                        }
                    } else {
                        ramdomnum(texts);
                        refresh_searchTextView();
                    }
                } catch (NullPointerException e) {
                    Toast.makeText(Search.this, "connection timeout", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
                break;
            case R.id.edittext_search:
                cancel.setVisibility(View.VISIBLE);
        }
    }

    /*
    换一批热门搜索
     */
    private void refresh_searchTextView() {
        for (int i = 0; i < data_num.size(); i++) {
            TextView tv = (TextView) searchLayout.getChildAt(i);
            tv.setText(data_num.get(i));
        }
    }

    /*
    搜索
     */
    private void SearchProduct(String name, int pageNum) {
        sr.Search_Result(name, "" + pageNum, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("TAG", "服务器爆炸了--from 搜索");
                Message msg = new Message();
                msg.what = GOTOSEARCH_FAIL;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (searched != null) {
                        searched.getData().clear();
                        searched = null;
                    }
                    Gson gson = new Gson();
                    String responsedata = response.body().string();
//                    searched = null;
                    searched = gson.fromJson(responsedata, Searched.class);
                    Message msg = new Message();
                    msg.what = GOTOSEARCH;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = GOTOSEARCH_FAIL;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    /*
    加载更多
     */
    private void moredata(final String name, String pageNum) {

        sr.Search_Result(name, pageNum, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("TAG", "服务器爆炸了--from moredata() ");
                Message msg = new Message();
                msg.what = ERRORDATA;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (searched != null) {
                        searched = null;
                    }
                    Log.d(TAG, "onResponse: name" + name + "page" + page);
                    Gson gson = new Gson();
                    String responsedata = response.body().string();
                    searched = gson.fromJson(responsedata, Searched.class);
                    Log.d(TAG, "onResponse: name" + name + "page" + page);
                    Message msg = new Message();
                    msg.what = LOGINMOREDATA;
                    handler.sendMessage(msg);
                } catch (JsonSyntaxException e) {
                    Message msg = new Message();
                    msg.what = ERRORDATA;
                    handler.sendMessage(msg);
                } catch (NullPointerException e) {
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /*
    根据footer的status,判断是否加载数据
     */
    private final int LOGINMORE = 1;
    private final int END = 2;
    private final int ERROR = 3;
    private final int NORMAL = 4;
    private int page = 1; //搜索结果的页码


    //根据footer_status看显示那个footer
    private void showFooter(int footer_status) throws NullPointerException {
        if (footer_status == 0) {
            footer_status = ERROR;
        }
        switch (footer_status) {
            case NORMAL:
                adapter.mfooterHolder.setdata(0);
                break;
            case LOGINMORE:  //加载更多数据
                adapter.mfooterHolder.setdata(LOGINMORE);
                break;
            case END:
                adapter.mfooterHolder.setdata(END);
                break;
            case ERROR:
                adapter.mfooterHolder.setdata(ERROR);
                break;
            default:
                adapter.mfooterHolder.setdata(ERROR);
                break;
        }
    }

    private RecycleListener mylistener = new RecycleListener(list) {
        @Override
        public void setNewPage(View view) {
            super.setNewPage(view);
            if (maxRuest < 50) {
                showFooter(LOGINMORE);
                moredata(searchthing, page + "");
            }
        }
    };

    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (refreshLayout.isRefreshing()) {
                return true;
            } else {
                return false;
            }
        }
    };

   private RecycleItemListener recycleItemListener;
}
